import subprocess
import rumps
from collections import OrderedDict
import time
import json

# 配置文件保存
try:
    with open("config.json", "r") as f:  # 以只读方式打开config.json文件
        config = json.load(f)  # 将json格式数据转换为字典
    print(config)  # 打印配置文件
except FileExistsError:  # 文件不存在
    config = {"自动退出": "1", "开启通知": "1"}
    with open("config.json", "x") as f:
        json.dump(config, f)  # 将字典转化为字符串

# PD 系统自动识别
(status, output) = subprocess.getstatusoutput("prlctl list -a")  # 获取 prlctl list -a 的命令返回结果
if status == 0:
    output = output.split('\n')
    SystemList = []
    for i, buff in enumerate(output):
        if i != 0:
            a = buff.split('-')
            print(i, ':', a[-1].split())
            SystemList.append(a[-1].strip())


# GUI界面
class GUIAPP(rumps.App):
    def __init__(self):
        super(GUIAPP, self).__init__(name='PD-START', title='',
                                     icon='/Volumes/Samsung PM981A/PythonProjects/PD_Start/icon/logo.icns',
                                     quit_button='退出')
        self.coin_menus = OrderedDict()
        self.menu.add(rumps.MenuItem(title='系统: '))
        if status == 0:
            for i in SystemList:
                if self.system_type(i) == "Windows 11":
                    self.coin_menus[i] = rumps.MenuItem(title=i, callback=self.start,
                                                        icon='/Volumes/Samsung PM981A/PythonProjects/PD_Start/icon/Windows11.png')
                    self.menu.add(self.coin_menus[i])
                elif self.system_type(i) == "Windows 10":
                    self.coin_menus[i] = rumps.MenuItem(title=i, callback=self.start,
                                                        icon='/Volumes/Samsung PM981A/PythonProjects/PD_Start/icon/Windows.png')
                    self.menu.add(self.coin_menus[i])
                elif self.system_type(i) == "Linux":
                    self.coin_menus[i] = rumps.MenuItem(title=i, callback=self.start,
                                                        icon='/Volumes/Samsung PM981A/PythonProjects/PD_Start/icon/linux.png')
                    self.menu.add(self.coin_menus[i])
                elif self.system_type(i) == "MacOS":
                    self.coin_menus[i] = rumps.MenuItem(title=i, callback=self.start,
                                                        icon='/Volumes/Samsung PM981A/PythonProjects/PD_Start/icon/macos.png')
                    self.menu.add(self.coin_menus[i])
                else:
                    pass


        else:
            self.coin_menus['错误'] = rumps.MenuItem(title='未检测到PD软件或系统 ')
            self.menu.add(self.coin_menus['错误'])

        self.menu.add(rumps.MenuItem(title='设置: '))
        self.coin_menus['自动退出'] = rumps.MenuItem(title='自动退出', callback=self.notice,
                                                 icon='/Volumes/Samsung PM981A/PythonProjects/PD_Start/icon/set.png')
        self.menu.add(self.coin_menus['自动退出'])
        if config['自动退出'] == '1':
            self.coin_menus['自动退出'].state = 1
        else:
            self.coin_menus['自动退出'].state = 0

        self.coin_menus['开启通知'] = rumps.MenuItem(title='开启通知', callback='self.notice',
                                                 icon='/Volumes/Samsung PM981A/PythonProjects/PD_Start/icon/tongzhi.png')
        self.menu.add(self.coin_menus['开启通知'])
        if config['开启通知'] == '1':
            self.coin_menus['开启通知'].state = 1
        else:
            self.coin_menus['开启通知'].state = 0

        self.coin_menus['关于'] = rumps.MenuItem(title='关于', callback=self.notice,
                                               icon='/Volumes/Samsung PM981A/PythonProjects/PD_Start/icon/help.png')
        self.menu.add(self.coin_menus['关于'])

        self.quit_button.icon = '/Volumes/Samsung PM981A/PythonProjects/PD_Start/icon/quit.png'

    def start(self, parm):
        print(parm.title)
        (status, output) = subprocess.getstatusoutput('open /Applications/Parallels\ Desktop.app')
        if status == 0:
            print('PD 启动成功')
            cmd = "prlctl start " + "\"" + parm.title + "\""
            (status, output) = subprocess.getstatusoutput(cmd)
            if status == 0:
                if self.coin_menus['开启通知'].state == 1:
                    rumps.notification("系统启动成功", parm.title, time.ctime())
                if self.coin_menus['自动退出'].state == 1:
                    rumps.quit_application()
                print("完成" + parm.title + "系统启动成功")
            else:
                if self.coin_menus['开启通知'].state == 1:
                    rumps.notification("系统启动失败", parm.title, time.ctime())
                print("错误" + parm.title + "系统启动失败")
        else:
            print("错误：PD启动失败，请确认是否安装PD虚拟机")
            rumps.alert("错误：PD启动失败，请确认是否安装PD虚拟机")

    def system_type(self, str):
        if str.find('Windows', 0, len(str)) != -1 and str.find('11', 0, len(str)) != -1:
            return 'Windows 11'
        elif str.find('Windows', 0, len(str)) != -1:
            return 'Windows 10'
        elif str.find('Win', 0, len(str)) != -1:
            return 'Windows 10'
        elif str.find('Ubuntu', 0, len(str)) != -1:
            return 'Linux'
        elif str.find('Fedora', 0, len(str)) != -1:
            return 'Linux'
        elif str.find('Debian', 0, len(str)) != -1:
            return 'Linux'
        elif str.find('Kali', 0, len(str)) != -1:
            return 'Linux'
        else:
            return 'MacOS'

    def prefs(self, _):
        rumps.alert(title='PD START', message="版本1.0")

    def set(self, sender):
        sender.state = not sender.state
        config['自动退出'] = str(sender.state)
        with open('config.json', 'w') as f:
            json.dump(config, f)
        print(sender)
        print(sender.state)

    def notice(self, sender):
        sender.state = not sender.state
        config['开启通知'] = str(sender.state)
        with open('config.json', 'w') as f:
            json.dump(config, f)
        print(sender)
        print(sender.state)


# 主程序
if __name__ == '__main__':
    pass
    GUIAPP().run()
